<?php

namespace App\Http\Controllers\Api;

use App\Model\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use function foo\func;

class CartController extends BaseController {
    private $user;
    public function __construct(){
        $this->user=$this->GetUser();
    }

    //购物车列表
    public function list(Request $request){
        if (isset($this->user['code'])){
            return json_encode(['msg'=>$this->user['msg']]);
        }

            $where['user_id']=$this->user['user_id'];
            $list=DB::table('cart')->where($where)->get()->each(function ($item,$key){
            $item->goods=DB::table('goods')->where('goods_id',$item->goods_id)->first();
            $item->sku=DB::table('goods_sku')->where('id',$item->goods_sku_id)->first();
            $item->image=$this->GetGoodsImg($item->goods_id);
            return $item;
        });

        return json_encode($list);
    }


    //添加购物车
    public function add(Request $request){
        $data=$request->all();
        // 购物车商品索引
        $data['index']=$data['goods_id'] . '_' . $data['goods_sku_id'];
        $data['user_id']=$this->user['user_id'];
        $data['create_time']=time();

        $where['user_id']=$this->user['user_id'];
        $where['index']=$data['index'];
        unset($data['token']);
        $check=DB::table('cart')->where($where)->first();
        if ($check){
            DB::table('cart')->where($where)->increment('goods_num');
        }else{
            DB::table('cart')->insert($data);
        }
        return json_encode(['code'=>1,'msg'=>'添加成功']);
    }

    //减少购物车商品数量
    public function sub(Request $request){
        $data=$request->all();
        // 购物车商品索引
        $where['user_id']=$this->user['user_id'];
        $where['index']=$data['goods_id'] . '_' . $data['goods_sku_id'];

        $check=DB::table('cart')->where($where)->first();
        if ($check->goods_num>1){
            DB::table('cart')->where($where)->decrement('goods_num');
            return json_encode(['code'=>1,'msg'=>'减少成功']);
        }else{
            return json_encode(['code'=>0,'msg'=>'不能在减少了']);
        }
    }


    //删除购物车
    public function del(Request $request){
        $id=$request->input('id');
        $res=DB::table('cart')->delete($id);
        if ($res){
            return ['code'=>1,'msg'=>'删除成功'];
        }else{
            return ['code'=>0,'msg'=>'删除失败'];
        }
    }





}
